package online_store.servlet;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import online_store.model.bus.UserBus;
import online_store.model.dto.UserDTO;

public class UpdateUserServlet extends HttpServlet{
	
	private UserBus userBus;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		userBus = new UserBus();
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		System.out.println("asdasd " + session.getAttribute("user_id"));
		
		int user_id = (int) session.getAttribute("user_id");
		String changePass = request.getParameter("change_password");
		
		System.out.println("changePass : " + changePass);
		 
		UserDTO user = new UserDTO();
		user.setUsername(request.getParameter("username"));
		user.setEmail(request.getParameter("email"));
		if(changePass != null && changePass.equals("true")){
			user.setOldPass(request.getParameter("current_password"));
			user.setNewPass(request.getParameter("new_password"));
		}
		
		String errorMessage = "";
		int rs = userBus.updateUser(user_id, user);
		
		if(rs == -1){
			errorMessage = "?errorMessage=duplicated-username";
		}else if(rs == -2){
			errorMessage = "?errorMessage=invalid-current-password";
		}
		
		if(errorMessage.equals("")){
			session.setAttribute("user_id", user.getId());
			session.setAttribute("username", user.getUsername());
		}
		response.sendRedirect(request.getContextPath() + "/user/userDetail.jsp" + errorMessage);
	}
}
